package com.kfm.spring.dao.impl;

import com.kfm.spring.dao.IAccountDao;
import com.kfm.spring.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(Account account) {
        String sql = "insert into account(uid, money) values(?, ?)";
        return jdbcTemplate.update(sql, account.getUid(), account.getMoney());
    }

    @Override
    public int update(Account account) {
        return 0;
    }

    @Override
    public int updateMoneyById(Integer id, Double money) {
        String sql = "update account set money = ? where id = ?";
        return jdbcTemplate.update(sql, money, id);
    }

    @Override
    public Account findById(Integer id) {
        String sql = "select * from account where id = ?";
        return jdbcTemplate.queryForObject(sql, new AccountRowMapper(), id);
    }

    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        return jdbcTemplate.query(sql, new AccountRowMapper());
    }

    public static class AccountRowMapper implements RowMapper<Account> {
        @Override
        public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setUid(rs.getInt("uid"));
            account.setMoney(rs.getDouble("money"));
            return account;
        }
    }
}
